package com.andreams.restaurant.persistence;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.andreams.restaurant.domain.Restaurant;

public class RestaurantDao {
	
	private Session session;
	
	public RestaurantDao(){
		session = HibernateUtil.getSessionFactory().getCurrentSession();
	}

	public void createRestaurant(String name, long latitude,
    		long longitude, long altitude, int rating) {
        Restaurant restaurant = new Restaurant();
        restaurant.setName(name);
        restaurant.setLatitude(latitude);
        restaurant.setLongitude(longitude);
        restaurant.setAltitude(altitude);
        if(rating > 0) restaurant.setRating(rating);
        session.save(restaurant);
    }
	

	
	@SuppressWarnings("unchecked")
	public List<Restaurant> getRestaurants(){
        List restaurants = session.createQuery("select r from Restaurant as r").list();
        List<Restaurant> results = new ArrayList<Restaurant>();
        for (Object object : restaurants) {
			if(object instanceof Restaurant){
				results.add((Restaurant) object);
			}
		}
        return results;
	}
	
	public Restaurant getRestaurant(long id){
        Query q = session.createQuery("select r from Restaurant as r where r.id =:id");
        q.setLong("id", id);
        Restaurant restaurant = null;
        if(q.uniqueResult() instanceof Restaurant){
        	restaurant = (Restaurant) q.uniqueResult();
        	System.out.println(restaurant.getName());
        }
        return restaurant;
	}
    
}
